package com.example.hao.flowercityfm.Fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.hao.flowercityfm.Files.Cache;
import com.example.hao.flowercityfm.HFAdapter.HomeDataAdapter;
import com.example.hao.flowercityfm.R;
import com.example.hao.flowercityfm.mvp.presenter.HomeFPresenter;
import com.example.hao.flowercityfm.pojo.HomeFragmentData;
import com.example.hao.flowercityfm.utils.HttpUtils;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * 首页
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment {

    private static final String TAG = "HomeFragment";
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.fab_upload)
    FloatingActionButton fabUpload;

    Unbinder unbinder;

    private HomeDataAdapter homeDataAdapter;
    private Cache cache;
    private SharedPreferences preferences;
    private SharedPreferences.Editor edit;


    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        cache = new Cache(context);
        preferences = context.getSharedPreferences(Cache.FM_DATA, Context.MODE_PRIVATE);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        readFileJson();
        return view;
    }

    /**
     * @return true 没有缓存json数据
     */
    private boolean isNotCache() {
        return preferences.getString(KEY, DEF_VALUE).equals(DEF_VALUE);
    }

    /**
     * 读取缓存
     */
    private void readFileJson() {
        if (isNotCache()) {
            initData();
        } else {
            String file = cache.readFile(FILE_NAME);
            if (file == null) {
                initData();
            } else {
                bindData(file);
            }
        }
    }

    private void initView() {

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshlayout) {
                initData();
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        rv.setLayoutManager(new LinearLayoutManager(getContext()));

        homeDataAdapter = new HomeDataAdapter(getActivity());
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                sumDy += dy;

                if (sumDy >= 1280 && lastSumDy < 1280) {
                    fabUpload.setVisibility(View.VISIBLE);
                } else if (sumDy <= 1280 && lastSumDy > 1280) {
                    fabUpload.setVisibility(View.GONE);
                }

                lastSumDy = sumDy;
            }
        });

    }

    private int sumDy = 0;
    private int lastSumDy = 0;

    public static final String HOME_DARA_URL = "https://api.myjson.com/bins/wrvso";

    private static final String KEY = "HF";
    private static final String VALUE = "999";

    private static final String DEF_VALUE = "null";

    private static final String FILE_NAME = "HFJson.txt";

    private void initData() {

        HttpUtils.method2(HOME_DARA_URL, new HttpUtils.OnOkCallBack() {
            @Override
            public void onFailure(@NonNull IOException e) {
                Log.e(TAG, "onFailure: " + e.getMessage());
            }

            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onResponse(@NonNull String jsonStr) {

                edit = preferences.edit();
                edit.putString(KEY, VALUE);
                edit.apply();

                bindData(jsonStr);
                cache.writeFile(FILE_NAME, jsonStr);

            }
        });
    }

    private void bindData(String data) {
        HomeFragmentData homeData = new Gson().fromJson(data, HomeFragmentData.class);

        rv.setAdapter(homeDataAdapter);
        homeDataAdapter.setHomeData(homeData);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * 回到item0项
     */
    @OnClick(R.id.fab_upload)
    public void onViewClicked() {
//        int top = rv.getTop();
//        rv.smoothScrollToPosition(0);
        rv.smoothScrollBy(0, -sumDy);
    }


}
